package bootstrap

import (
	"database/sql"
	"fmt"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/spf13/viper"
	"go_payment/dao"
	"os"
)

func Bootstrap() {
	initConfig()
	initDb()
	initRedis()
}

func initConfig() {
	path, _ := os.Getwd()
	viper.AddConfigPath(path)
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	if err := viper.ReadInConfig(); err != nil {
		panic(err)
	}
}

func initDb() {
	driver := viper.GetString("database.driver")
	username := viper.GetString("database.username")
	password := viper.GetString("database.password")
	host := viper.GetString("database.host")
	port := viper.GetInt("database.port")
	dbname := viper.GetString("database.dbname")
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", username, password, host, port, dbname)
	db, err := sql.Open(driver, dsn)
	if err != nil {
		panic(err)
	}
	dao.SetDB(db)
}

func initRedis() {
	host := viper.GetString("redis.host")
	port := viper.GetInt("redis.port")
	database := viper.GetInt("redis.database")
	auth := viper.GetString("redis.auth")
	client := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", host, port),
		DB:       database,
		Password: auth,
	})

	_, err := client.Ping().Result()
	if err != nil {
		panic(err)
	}
	dao.SetRDB(client)
}
